﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace KD.Sms.Task
{
    public class Cyj
    {
        /// <summary>
        /// 本类的唯一实例
        /// </summary>
        private static Cyj OWNER = null;
        public event EventHandler<ActiveReadEventArgs> PlcDataReadOut;

        /// <summary>
        /// 当前连接状态
        /// </summary>
        private bool _bIsConnect { set; get; }
        /// <summary>
        /// 获取类的唯一实例
        /// </summary>
        /// <returns></returns>
        public static Cyj Instance
        {
            get
            {
                if (Cyj.OWNER == null)
                {
                    Cyj.OWNER = new Cyj();
                }
                return Cyj.OWNER;
            }
        }

        private PLC _objPlc;
        /// <summary>
        /// 启动封装机PLC
        /// </summary>
        /// <param name="device"></param>
        /// <param name="ip"></param>
        /// <param name="cycle"></param>
        /// <param name="begin"></param>
        /// <param name="length"></param>
        public bool DoStart(string device, string ip, int cycle, int begin, int length)
        {
            _objPlc = new PLC(device, ip, cycle, begin, length);
            _objPlc.ActiveReadEvent += OnActiveReadEvent;
            _bIsConnect= _objPlc.DoStart();
            return _bIsConnect;
        }

        /// <summary>
        /// 读取数据后返回
        /// </summary>
        /// <param name="send"></param>
        /// <param name="e"></param>
        private void OnActiveReadEvent(object send, ActiveReadEventArgs e)
        {
            if (e.E_ReadValue != null)
                EventHelper.DispatchEventAsync<ActiveReadEventArgs>(this, this.PlcDataReadOut, e);
        }

        /// <summary>
        /// 往地址写入值
        /// </summary>
        /// <param name="address"></param>
        /// <param name="value"></param>
        public bool DoWrite(int address, object value)
        {
          return _bIsConnect ? _objPlc.DoWrite(address, value) : false;
        }

        /// <summary>
        /// 往地址写入值
        /// </summary>
        /// <param name="address"></param>
        /// <param name="value"></param>
        public bool DoWrite(int address, short value)
        {
            return _bIsConnect ? _objPlc.DoWrite(address, value) : false;
        }

        /// <summary>
        /// 往地址写入值
        /// </summary>
        /// <param name="address"></param>
        /// <param name="value"></param>
        public bool DoWrite(int address, short[] value)
        {
            return _bIsConnect ? _objPlc.DoWrite(address, value) : false;
        }
    }
}
